import React, { useState } from 'react';
import {
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableRow,
  Paper,
  Button,
  Typography,
  Chip,
  Divider,
} from '@mui/material';
import { styled } from '@mui/material/styles';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';
import FileCopyOutlinedIcon from '@mui/icons-material/FileCopyOutlined';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import AddIcon from '@mui/icons-material/Add';
import GridLayout from '../general/GridLayout';
import DialogBox from '../general/DialogBox';
import Utils from '../../utils/Utils';
import { EXPERIMENT_STATE, EXPERIMENT_TEXTS, EXPERIMENT_VIEWS } from '../../constants';
import { experimentGrey, experimentInputColor } from '../../theme';

const StyledTableContainer = styled(TableContainer)(({ theme }) => ({
  maxHeight: 'calc(100% -60vh)',
  overflow: 'auto',
  '&::-webkit-scrollbar': {
    height: theme.spacing(1),
  },
  '& .MuiTable-root': {
    '& .experimentHead': {
      fontSize: '1rem',
    },
    '& .experimentHeadIcon': {
      fontSize: '1rem',
    },
    '& .experimentDate': {
      fontStyle: 'italic',
      fontWeight: 300,
      fontSize: '1rem',
      color: experimentGrey,
      whiteSpace: 'nowrap',
    },
    '& .experimentIcon': {
      color: experimentGrey,
      minWidth: 'auto',
      '& .MuiSvgIcon-root': {
        fontSize: '1.2rem',
      },
    },
    '& .MuiChip-label': {
      color: experimentGrey,
      fontSize: '0.77rem',
      fontWeight: 600,
    },
    '& .MuiChip-root': {
      background: experimentInputColor,
      height: theme.spacing(3.2),
    },
    '& .MuiChip-deleteIcon': {
      marginRight: theme.spacing(0.4),
    },
    '& .MuiTableCell-root': {
      padding: theme.spacing(1, 2),
      '&:nth-child(1)': {
        width: '18.75rem',
        '& button': {
          maxWidth: '50vw',
          justifyContent: 'inherit',
        },
        '& h6': {
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap',
          overflow: 'hidden',
        },
      },
      '&:nth-child(2)': {
        width: '9.375rem',
      },
    },
    '& .MuiChip-icon': {
      color: experimentGrey,
    },
    '& .MuiDivider-vertical': {
      height: theme.spacing(4),
      background: 'rgba(255, 255, 255, 0.3)',
    },
    '& .MuiTableCell-alignRight': {
      width: theme.spacing(6),
      paddingLeft: 0,
    },
    '& .MuiTableCell-alignCenter': {
      width: theme.spacing(6),
    },
  },
}));

interface Experiment {
  name: string;
  timestamp: string;
  state: string;
  [key: string]: any;
}

interface ExperimentsProps {
  experiments?: Experiment[];
  setEditState?: (state: boolean) => void;
  setExperimentName?: (name: string | null) => void;
  cloneExperiment?: (name: string) => void;
  removeExperiment?: (name: string) => void;
  setView?: (view: string) => void;
  [key: string]: any;
}

/**
 * Experiments Component
 * Lists all experiments with actions (edit, clone, delete)
 * Placeholder implementation - full functionality pending
 */
const Experiments: React.FC<ExperimentsProps> = ({
  experiments = [],
  setEditState,
  setExperimentName,
  cloneExperiment,
  removeExperiment,
  setView,
  ...otherProps
}) => {
  const [dialogOpen, setDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [cloneDialogOpen, setCloneDialogOpen] = useState(false);
  const [actionExperimentName, setActionExperimentName] = useState<string | null>(null);

  const deleteExperiment = (actionConfirmed: boolean): void => {
    if (actionConfirmed && actionExperimentName && removeExperiment) {
      removeExperiment(actionExperimentName);
    }
    setDeleteDialogOpen(false);
    setActionExperimentName(null);
  };

  const viewExperiment = (name: string): void => {
    if (setEditState) setEditState(false);
    if (setExperimentName) setExperimentName(name);
    if (setView) setView(EXPERIMENT_VIEWS.viewExperiment);
  };

  const createExperimentScreen = (actionConfirmed: boolean): void => {
    setDialogOpen(false);
    if (setEditState) setEditState(false);
    if (setExperimentName) setExperimentName(null);
    if (setView) {
      setView(!actionConfirmed ? EXPERIMENT_VIEWS.list : EXPERIMENT_VIEWS.edit);
    }
  };

  const openEditExperiment = (name: string): void => {
    if (setExperimentName) setExperimentName(name);
    if (setView) setView(EXPERIMENT_VIEWS.edit);
    if (setEditState) setEditState(true);
  };

  const openCloneDialog = (name: string): void => {
    setActionExperimentName(name);
    setCloneDialogOpen(true);
  };

  const openDeleteDialog = (name: string): void => {
    setActionExperimentName(name);
    setDeleteDialogOpen(true);
  };

  const onCloneExperimentAction = (actionConfirmed: boolean): void => {
    if (actionConfirmed && actionExperimentName && cloneExperiment) {
      cloneExperiment(actionExperimentName);
    }
    setCloneDialogOpen(false);
    setActionExperimentName(null);
  };

  const sortedExperiments = [...experiments].sort(
    (e1, e2) => new Date(e2.timestamp).getTime() - new Date(e1.timestamp).getTime()
  );

  return (
    <>
      <GridLayout>
        <div className="scrollDiv">
          <Box>
            <StyledTableContainer>
              <Table aria-label="simple table">
                <TableBody>
                  {sortedExperiments.map((experiment) => (
                    <TableRow key={experiment?.name}>
                      <TableCell component="th" scope="row">
                        <Button onClick={() => viewExperiment(experiment?.name)}>
                          <Typography variant="h6" className="experimentHead">
                            {experiment?.name}
                          </Typography>
                          <ChevronRightIcon className="experimentHeadIcon" />
                        </Button>
                      </TableCell>
                      <TableCell align="left">
                        <Typography variant="h6" className="experimentDate">
                          {Utils.formatDate(experiment?.timestamp)}
                        </Typography>
                      </TableCell>
                      <TableCell align="left">
                        {[
                          EXPERIMENT_STATE.PENDING,
                          EXPERIMENT_STATE.SIMULATING,
                          EXPERIMENT_STATE.INSTANTIATING,
                        ].includes(experiment?.state as any) ? (
                          <Chip
                            icon={
                              <Box
                                className="MuiChipLoader"
                                sx={{
                                  border: '3px solid rgba(196, 196, 196, 0.3)',
                                  borderRadius: '50%',
                                  borderTop: `3px solid ${experimentGrey}`,
                                  width: '24px',
                                  height: '24px',
                                  animation: 'spin 2s linear infinite',
                                  '@keyframes spin': {
                                    '0%': { transform: 'rotate(0deg)' },
                                    '100%': { transform: 'rotate(360deg)' },
                                  },
                                }}
                              />
                            }
                            label={experiment?.state}
                          />
                        ) : (
                          <Chip label={experiment?.state} />
                        )}
                      </TableCell>
                      <TableCell align="right">
                        <Button
                          className="experimentIcon"
                          onClick={() =>
                            experiment?.state === EXPERIMENT_STATE.DESIGN
                              ? openEditExperiment(experiment?.name)
                              : openCloneDialog(experiment?.name)
                          }
                        >
                          {experiment?.state === EXPERIMENT_STATE.DESIGN ? (
                            <EditIcon />
                          ) : (
                            <FileCopyOutlinedIcon />
                          )}
                        </Button>
                      </TableCell>
                      <TableCell align="center">
                        <Divider orientation="vertical" />
                      </TableCell>
                      <TableCell align="right">
                        <Button
                          className="experimentIcon"
                          onClick={() => openDeleteDialog(experiment?.name)}
                        >
                          <DeleteIcon />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </StyledTableContainer>
          </Box>
        </div>
        <Box
          className="scrollbar scrollchild"
          mt={1}
          display="flex"
          flexWrap="wrap"
          flex="none"
        >
          <Box>
            <Button color="primary" startIcon={<AddIcon />} onClick={() => setDialogOpen(true)}>
              CREATE NEW EXPERIMENT
            </Button>
          </Box>
        </Box>
      </GridLayout>
      <DialogBox
        open={dialogOpen}
        onDialogResponse={createExperimentScreen}
        textForDialog={{
          heading: EXPERIMENT_TEXTS.CREATE_EXPERIMENT,
          content: EXPERIMENT_TEXTS.DIALOG_MESSAGE,
        }}
      />
      <DialogBox
        open={deleteDialogOpen}
        onDialogResponse={deleteExperiment}
        textForDialog={{
          heading: EXPERIMENT_TEXTS.DELETE_EXPERIMENT,
          content: EXPERIMENT_TEXTS.DELETE_DIALOG_MESSAGE,
        }}
      />
      <DialogBox
        open={cloneDialogOpen}
        onDialogResponse={onCloneExperimentAction}
        textForDialog={{
          heading: EXPERIMENT_TEXTS.CLONE_EXPERIMENT,
          content: EXPERIMENT_TEXTS.CLONE_EXPERIMENT_MESSAGE,
        }}
      />
    </>
  );
};

export default Experiments;

